﻿using Microsoft.EntityFrameworkCore;
using Rbac.Domain.Admins;
using Rbac.Domain.Menus;
using Rbac.Domain.RoleMenus;
using Rbac.Domain.Roles;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rbac.Domain
{
    public class RbacDbContext : DbContext
    {
        public RbacDbContext(DbContextOptions options) : base(options)
        {

        }
        public DbSet<Admin> Admins { get; set; }

        public DbSet<Menu> Menus { get; set; }

        public DbSet<Role> Roles { get; set; }

        public DbSet<RoleMenu> RoleMenus { get; set; }


        /// <summary>
        /// FluentAPI
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Admin>(config => {
                config.HasKey(x => x.AdminId);
                config.Property(m => m.UserName).HasMaxLength(50).IsRequired();
                config.Property(m => m.Password).HasMaxLength(50).IsRequired();
                config.Property(m => m.FullName).HasMaxLength(50);
                config.Property(m => m.HeaderImage).HasMaxLength(500);
                config.Property(x => x.LastLoginIP).HasMaxLength(50);
            });

            modelBuilder.Entity<Menu>(config => {
                config.HasKey(x => x.MenuId);
                config.Property(m => m.MenuName).HasMaxLength(50).IsRequired();
                config.Property(m => m.MenuCode).HasMaxLength(50).IsRequired();
                config.Property(m => m.ComponentPath).HasMaxLength(50);
                config.Property(m => m.RoutePath).HasMaxLength(500);
                config.Property(x => x.Icon).HasMaxLength(50);
                config.Property(x => x.ParentPath).HasMaxLength(50);
            });

            //主外键关系
            modelBuilder.Entity<Role>(config => {
                config.Property(m => m.RoleName).HasMaxLength(50).IsRequired();
            });

            //主外键关系
            modelBuilder.Entity<RoleMenu>(config => {
                config.HasOne<Role>().WithMany().HasForeignKey(m => m.RoleId);
                config.HasOne<Menu>().WithMany().HasForeignKey(m => m.MenuId);
            });

            base.OnModelCreating(modelBuilder);
        }
    }
}